@extends('backstage.layout.master')
@section('title', '创建产品')
@section('style')
<link rel="stylesheet" href="/assets/css/dropzone.css" />
@stop
@section('content')
    <div class="breadcrumbs" id="breadcrumbs">
        <script type="text/javascript">
            try {
                ace.settings.check('breadcrumbs', 'fixed')
            } catch (e) {
            }
        </script>

        <ul class="breadcrumb">
            <li>
                <i class="icon-home home-icon"></i>
                <a href="backstage/home">主页</a>
            </li>

            <li class="active">
                <a href="backstage/products/list/1">产品列表</a>
            </li>
            <li>
                创建产品
            </li>
        </ul><!-- .breadcrumb -->
    </div>

    <div class="page-content">
        <div class="row">
            <div class="col-xs-12">
                <!-- PAGE CONTENT BEGINS -->
                <div class="page-header">
                    <h1>
                        创建产品
                    </h1>
                </div>
                <div class="row">
                    <div class="col-xs-12">
                        <form id="myform" class="form-horizontal" role="form" action="backstage/products/create-product-from-backstage" method="post" enctype="multipart/form-data" onsubmit="return check_data();">
                            <input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
                            <input type="hidden" name="colour_id" id="colour_id" value="">
                            <input type="hidden" name="product_temp_id" value="" id="product_temp_id">
                            <div class="row" id="layer-out">
                                <div class="col-xs-12">
                                    <label class="col-sm-4 center"> 模板选择 </label>
                                    <div class="col-sm-4 center">
                                        <select id="search">
                                            @if(isset($temps)&& count($temps) > 0)
                                                @foreach($temps as $temp)
                                                    <option value="{{isset($temp->product_temp_id) ? $temp->product_temp_id : ''}}">
                                                        {{isset($temp->name) ? $temp->name : ''}}({{isset($temp->brand_name) ? $temp->brand_name : ''}})
                                                    </option>
                                                @endforeach
                                            @else
                                                    <option value="">占无可用模版</option>
                                            @endif
                                        </select>
                                    </div>
                                    <div class="col-sm-4 center">
                                        <button type="button" onclick="find_product_temp()">
                                             搜索
                                        </button>
                                    </div>
                                </div>
                                <div class="col-xs-12" id="search-result" style="margin-top: 30px;">
                                    <table id="search-list" class="table table-striped table-bordered table-hover">
                                        
                                    </table>
                                </div>
                            </div> 
                            <div class="space-4"></div>
                            <div class="clearfix form-actions">
                                <div class="col-md-offset-5 col-md-7">
                                    <button class="btn btn-info" type="submit">
                                        <i class="icon-ok bigger-110"></i>
                                        保存
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>    
            </div>
        </div><!-- /.row -->
    </div><!-- /.page-content -->
    <div class="row" id="layer-source-out" style="display: none;margin-top: 20px">
        <input type="hidden" class="position_input" value="">
        <div class="col-xs-12">
            <label class="col-sm-4 center"> 素材类型 </label>
            <div class="col-sm-4 center">
                <select class="width-100" name="source_type" id="source_type">
                    <option value="0">请选择素材类型</option>
                    <option value="1">系统素材</option>
                    <option value="2">自定义素材</option>
                </select>
            </div>
        </div>
        <div class="col-xs-12" id="tag-col" style="display: none;">
            <label class="col-sm-4 center"> 素材标签 </label>
            <div class="col-sm-4 center">
                <select id="tag-list" class="width-100">
                    
                </select>
            </div>
            <div class="col-sm-4 center">
                <button onclick="find_source_list(1);">
                     搜索
                </button>
            </div>
        </div>
        <div class="col-xs-12" id="search-source-result" style="display: none;margin-top: 30px;margin-bottom: 30px;">
            <div class="col-xs-12">
                <table id="search-source-list" class="table table-striped table-bordered table-hover">
                    <thead>
                        <tr>
                            <th width="50px">素材编号</th>
                            <th class="hidden-480" width="120px">缩略图</th>
                            <th>素材名称</th>
                            <th>原价</th>
                            <th>优惠价</th>
                            <th width="60px">操作区</th>
                        </tr>
                    </thead>
                    <tbody>

                    </tbody>
                </table>
            </div>
            <div class="col-xs-12">
                 <div class="dataTables_paginate paging_bootstrap">
                    <a style="cursor:pointer;" class="prev">上一页</a> 
                    <span class="current-page"></span> / <span class="all-page"></span>
                    <a style="cursor:pointer;" class="next">下一页</a>
                    <span><select class="page-choose"></select></span>
                </div>
            </div>
        </div>

        <div class="col-xs-12" id="search-source-custom" style="display: none;margin-top: 30px;margin-bottom: 30px;">
            <!-- PAGE CONTENT BEGINS -->
            <div id="dropzone">
                <form action="/backstage/products/bluk-add-source-pic" class="dropzone">
                    <input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
                    <div class="fallback">
                        <input name="file" type="file" multiple="" />
                    </div>
                </form>
            </div><!-- PAGE CONTENT ENDS -->
        </div><!-- /.col -->
    </div>
@stop
@section('script')
    <script src="/js/dropzone/dropzone.min.js"></script>
    <script type="text/javascript" src="backstage/js/layer/layer.js"></script>
    <script type="text/javascript">
        var index;
        jQuery(function($){
            try {
                $(".dropzone").dropzone({
                    paramName: "file", // The name that will be used to transfer the file
                    maxFilesize: 10, // MB

                    //addRemoveLinks : true,
                    dictDefaultMessage :
                    '<span class="bigger-150 bolder"><i class="icon-caret-right red"></i> Drop files</span> to upload \
                    <span class="smaller-80 grey">(or click)</span> <br /> \
                    <i class="upload-icon icon-cloud-upload blue icon-3x"></i>'
                    ,
                    dictResponseError: '上传文件过程中发生错误!',

                    //change the previewTemplate to use Bootstrap progress bars
                    previewTemplate: "<div class=\"dz-preview dz-file-preview\">\n  <div class=\"dz-details\">\n    <div class=\"dz-filename\"><span data-dz-name></span></div>\n    <div class=\"dz-size\" data-dz-size></div>\n    <img data-dz-thumbnail />\n  </div>\n  <div class=\"progress progress-small progress-striped active\"><div class=\"progress-bar progress-bar-success\" data-dz-uploadprogress></div></div>\n  <div class=\"dz-success-mark\"><span></span></div>\n  <div class=\"dz-error-mark\"><span></span></div>\n  <div class=\"dz-error-message\"><span data-dz-errormessage></span></div>\n</div>",
                    sending: function(file, xhr, formData) {
                            formData.append("filesize", file.size);
                        },
                    success: function (file, response, e) {
                            if (response.state!='M00000') {
                                $(file.previewTemplate).children('.dz-error-mark').css('opacity', '1');
                                file.previewElement.classList.add("dz-error");
                                $(file.previewElement).find('.dz-error-message').text(response.message);
                            }else {
                                file.previewElement.classList.add("dz-success");
                                $(file.previewTemplate).children('.dz-success-mark').css('opacity', '1');
                                var str = '<tr><td>'+response.result.creative_id+'</td><td>自定义素材</td><td><img src="'+response.result.thumbnail+'" style="width: 120px;"></td><td>'+response.result.name+'</td><td>原价：<input data="'+response.result.creative_id+'" type="number" min="0" step="0.01" value="'+response.result.price+'" class="price" style="width:100px;"> / 优惠价：<input data="'+response.result.creative_id+'" type="number" min="0" step="0.01" value="'+response.result.preferential_price+'" class="preferential_price" style="width:100px;"></td><td><a href="javascript:;" class="delete-source" data="'+response.result.creative_id+'">删除</a></td></tr>';
                                var p = $(".position_input").val();
                                $("#"+p).after(str);
                                var arr=p.split("_"); 
                                var image_input = '<input type="hidden" id="source_'+response.result.creative_id+'" name="source'+'_'+arr[1]+'_2[]" value="'+response.result.creative_id+'">';

                                $("#myform").prepend(image_input);
                            }
                    }
                });
                } catch(e) {
                    alert('当前浏览器版本太低，插件不支持此浏览器!');
                }

        });
        var filechange = function (event,th) {
            var files = event.target.files, file;
            if (files && files.length > 0) {
                // 获取目前上传的文件
                file = files[0];// 文件大小校验的动作
                // if (file.size > 1024 * 1024 * 10) {
                //     alert('图片大小不能超过 2MB!');
                //     return false;
                // }
                // 获取 window 的 URL 工具
                var URL = window.URL || window.webkitURL;
                // 通过 file 生成目标 url
                var imgURL = URL.createObjectURL(file);
                //用attr将img的src属性改成获得的url
                $("#"+th).attr("src", imgURL);
                //$("#img-change").attr("src", imgURL);

            }
        };
        $("#product_temp_id").click(function(){
            $('#layer-out').show();
            // index = layer.open({
            //   type: 1, 
            //   title: '请选择模板',
            //   area: ['500px','300px'],
            //   scrollbar: false,
            //   content: $('#layer-out')
            // });
        });
        $(".prev").click(function(){
            var page = parseInt($(".current-page").html())-1;
            if(page <= 0){
                layer.msg('已经是第一页');
                return;
            }
            find_source_list(page);
        });
        $(".next").click(function(){
            var page = parseInt($(".current-page").html())+1;
            var all_page = parseInt($(".all-page").html());
            if(page > all_page){
                layer.msg('已经是最后一页');
                return;
            }
            find_source_list(page);
        });
        $(".page-choose").change(function(){
            find_source_list(parseInt($(this).val()));
        });
        $("#myform").on('click','#add-source',function(){
            index = layer.open({
                type: 1, 
                title: '请选择素材',
                area: ['800px','500px'],
                scrollbar: false,
                content: $('#layer-source-out')
            });
            $(".position_input").val($(this).attr("data"));
        });

        $("#myform").on('change','.price',function(){
            var price = parseInt($(this).val());
            var creative_id = $(this).attr('data');
            $.ajax({
                url:"/backstage/products/update-price",
                type:"post",
                data:{"creative_id":creative_id,"price":price},
                datatype:"json",
                success:function(re){
                    console.log(re);
                    if(re.state=="M00000"){
                        layer.msg(re.message);
                        return;
                    }
                    layer.msg(re.message);
                    return;
                },
                error:function(){
                    layer.msg('系统繁忙,请稍后重试');
                    return;
                }
            });
        });

        $("#myform").on('change','.preferential_price',function(){
            var preferential_price = parseInt($(this).val());
            var creative_id = $(this).attr('data');
            $.ajax({
                url:"/backstage/products/update-price",
                type:"post",
                data:{"creative_id":creative_id,"preferential_price":preferential_price},
                datatype:"json",
                success:function(re){
                    console.log(re);
                    if(re.state=="M00000"){
                        layer.msg(re.message);
                        return;
                    }
                    layer.msg(re.message);
                    return;
                },
                error:function(){
                    layer.msg('系统繁忙,请稍后重试');
                    return;
                }
            });
        });

        $("#myform").on('click','.delete-source',function(){
            var source_pic_id = $(this).attr('data');
            $("#source_"+source_pic_id).remove();
            $(this).parent().parent().remove();
        });

        $("#layer-source-out").on('change','#source_type',function(){
            var source_type = $("#source_type option:selected").val();
            if(source_type == 0){
                $("#tag-col").hide();
                $("#search-source-result").hide();
                $("#search-source-custom").hide();
                return;
            }else if(source_type == 1){
                var product_temp_id = $("#product_temp_id").val();
                search_tag_list(product_temp_id);
                //系统素材
                $("#tag-col").show();
                $("#search-source-result").show();
                $("#search-source-custom").hide();
                return;
            }else{
                //自定义素材
                $("#search-source-custom").show();
                $("#tag-col").hide();
                $("#search-source-result").hide();
            }
        });
        function add_source_to_position(source_pic_id, small_image, source_pic_name, preferential_price, price)
        {
            var str = '<tr><td>'+source_pic_id+'</td><td>系统素材</td><td><img src="'+small_image+'" style="width: 120px;"></td><td>'+source_pic_name+'</td><td>原价：'+price+' / 优惠价：'+preferential_price+'</td><td><a href="javascript:;" class="delete-source" data="'+source_pic_id+'">删除</a></td></tr>';
            var p = $(".position_input").val();
            $("#"+p).after(str);
            var arr=p.split("_"); 
            var image_input = '<input type="hidden" id="source_'+source_pic_id+'" name="source'+'_'+arr[1]+'_1[]" value="'+source_pic_id+'">';

            $("#myform").prepend(image_input);
        }

        function search_tag_list(product_temp_id)
        {
            $.ajax({
                url:"/backstage/products/search-tag-list",
                type:"post",
                data:{"product_temp_id":product_temp_id},
                datatype:"json",
                success:function(re){
                    console.log(re);
                    if(re.state=="M00000"){
                        var str = '';
                        var each = re.result;
                        for(var i=0;i<each.data.length;i++){
                            str = str + '<option value="'+each.data[i].tag_id+'">'+each.data[i].tag_name+'</option>';
                        }
                        $("#tag-list").empty();
                        $("#tag-list").append(str);
                        return;
                    }
                    layer.msg(re.message);
                    return;
                },
                error:function(){
                    layer.msg('系统繁忙,请稍后重试');
                    return;
                }
            });
        }

        function find_source_list(page)
        {
            var tag_id = $("#tag-list option:selected").val();
            if(tag_id == '' || tag_id == undefined) return ;
            var product_temp_id = $("#product_temp_id").val();
            if(page == '') page=1;
            $.ajax({
                url:"/backstage/products/source-pic-list",
                type:"post",
                data:{"product_temp_id":product_temp_id,'tag_id':tag_id,'page':page},
                datatype:"json",
                success:function(re){
                    console.log(re);
                    if(re.state=="M00000"){
                        var str = '';
                        var each = re.result;
                        for(var i=0;i<each.data.length;i++){
                            str = str + '<tr><td>'+each.data[i].source_pic_id+'</td><td><img style="width:120px;" src="'+each.data[i].small_image+'"></td><td>'+each.data[i].source_pic_name+'</td><td>'+each.data[i].original_price+'</td><td>'+each.data[i].preferential_price+'</td><td><a href="javascript:;" class="add-source-a" onclick="add_source_to_position(&#39;'+each.data[i].source_pic_id+'&#39;,&#39;'+each.data[i].small_image+'&#39;,&#39;'+each.data[i].source_pic_name+'&#39;,&#39;'+each.data[i].preferential_price+'&#39;,&#39;'+each.data[i].original_price+'&#39;);">添加</a></td></tr>';
                        }
                        $("#search-source-list tbody").empty();
                        $("#search-source-list tbody").append(str);
                        $(".current-page").html(each.current_page);
                        $(".all-page").html(each.total_page);
                        $(".page-choose").empty();
                        var page_str = '';
                        for(var i=0;i<each.total_page;i++){
                            if((i+1) == each.current_page){
                                page_str = page_str + '<option value="'+(i+1)+'" selected>'+(i+1)+'</option>';
                            }else{
                                page_str = page_str + '<option value="'+(i+1)+'">'+(i+1)+'</option>';
                            }
                        }
                        $(".page-choose").append(page_str);
                        return;
                    }
                    layer.msg(re.message);
                    return;
                },
                error:function(){
                    layer.msg('系统繁忙,请稍后重试');
                    return;
                }
            });
        }

        function find_product_temp(){
            // var html = '<div class="col-xs-12">nihao</div>';
            // $("#layer-out").append(html);
            var product_temp_id = $("#search option:selected").val();
            if(product_temp_id == '' || product_temp_id == undefined) return ;
            $("#search-list") . html("");
            $.ajax({
                url:"/backstage/order/get-product-info",
                type:"post",
                data:{"product_temp_id":product_temp_id},
                datatype:"json",
                success:function(re){
                    console.log(re);
                    if(re.state=="M00000"){
                        var str = '';
                        if(re.result.temp == undefined || re.result.temp.length == 0){
                            str = '<tr><td colspan="4">暂无相关信息</td></tr>';
                        }else{
                            str = get_product_temp_str(re);
                        }
                        $("#search-list") . html(str);
                        return;
                    }
                    layer.msg(re.message);
                    return;
                },
                error:function(){
                    layer.msg('系统繁忙,请稍后重试');
                    return;
                }
            });
        }

        function get_product_temp_str(re){
            var str = '';
            var each = re.result;
            $("#product_temp_id").val(each.temp.product_temp_id);
            str += '<tr>' +
                        '<td id="tempname_'+each.temp.product_temp_id+'" colspan="4">' +
                            each.temp.name + '(' + each.temp.brand_name + ')'+
                        '</td>' +
                        '<td colspan="4">' +
                            '可选颜色 : <select id = "colour">';
                         for(var a=0;a<each.colours.length;a++){
            str +=              '<option data="' + each.colours[a].colour_id + '" value="' + each.colours[a].colour_name + '">' +
                                    each.colours[a].colour_name +
                                '</option>';
                         }             
            str +=          '</select>' +
                        '</td>' +
                    '</tr>';
                    for(var a=0;a<each.position.length;a++){
                        var input_poi = '<input type="hidden" name="positions[]" value="'+each.position[a].position_type+'">';
                        $("#myform").prepend(input_poi);

            str = str + '<tr id="position_'+each.position[a].position_type+'_'+each.temp.product_temp_id+'"><td colspan="6"><label class="col-sm-4">'+each.position[a].position_name+'</label><div class="col-sm-4"><button class="btn btn-info" id="add-source" data="position_'+each.position[a].position_type+'_'+each.temp.product_temp_id+'" type="button">添加素材（多选）</button></div></td></tr><tr><td colspan="4">添加预览图<input type="file" id="add-preview" name="preview_'+each.position[a].position_type+'" data="position_'+each.position[a].position_type+'_'+each.temp.product_temp_id+'" onchange="filechange(event,&#39;preview_'+each.position[a].position_type+'&#39;)"><img style="width:240px;" id="preview_'+each.position[a].position_type+'" src=""></td><td colspan="4">添加打印图<input id="add-print" name="print_'+each.position[a].position_type+'" data="position_'+each.position[a].position_type+'_'+each.temp.product_temp_id+'" type="file" onchange="filechange(event,&#39;print_'+each.position[a].position_type+'&#39;)"><img style="width:240px;" id="print_'+each.position[a].position_type+'" src=""></td></tr>';
                    }

            return str;
        }


        function check_data()
        {
            var product_temp_id = $("#product_temp_id").val();
            if(product_temp_id == '' || product_temp_id == undefined){
                layer.msg('请选择模板');
                return false;
            }
            var colour_id = $("#colour option:selected").attr("data");
            if(colour_id == '' || colour_id == undefined){
                layer.msg('请选择颜色');
                return false;
            }
            $("#colour_id").val(colour_id);
        }
    </script>
@stop